import React, {Component} from 'react'
import StyleUtils from "../../res/styles/StyleUtils";
import Navigation from "../../custom/Navigation";
import I18n from '../../res/language/i18n'
import {
    DeviceEventEmitter,
    Image,
    ListView,
    RefreshControl,
    StyleSheet,
    Text,
    TouchableHighlight,
    TouchableOpacity,
    View
} from "react-native";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import CommonUtils from "../../common/CommonUtils";
import AlertDialog from "../../custom/AlertDialog";
import GoodsPage from "./GoodsPage";
import ArticleDetail from "../article/ArticleDetail";

let ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2,
});
export default class CollectionPage extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.userInfo = null;


        this.state = {
            loading: false,
            refreshing: true,
            dataSource: ds,
            data: [],
            alertVisible: false,
            deleteData: {i: -1, data: null},
        };
    }


    componentWillUnmount() {
        this.iparNetwork = null;
        this.userInfo = null;
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                this.userInfo = JSON.parse(result);
                this.onLoadData();
            });
    }


    /**
     * 获取数据
     */
    onLoadData() {

        this.setState({
            refreshing: true,
        });

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'getCollection?', 'user_id=' + this.userInfo.main_user_id)
            .then((result) => {

                if (result.code === 200) {
                    this.setState({
                        loading: false,
                        refreshing: false,
                        dataSource: ds.cloneWithRows(result.data),
                        data: result.data,
                    })
                } else {
                    this.setState({
                        loading: false,
                        refreshing: false,
                    });
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }

            })
            .catch((error) => {
                this.setState({
                    loading: false,
                    refreshing: false,
                });
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('CollectionPage----deleteCollection--', error)
            })

    }

    /**
     * 删除收藏
     */
    deleteCollection(data, position) {
        if (!data.obj_id) {
            DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            return;
        }

        this.setState({
            loading: true,
        });


        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'deleteCollection?', 'id=' + data.id)
            .then((result) => {
                this.setState({
                    loading: false,
                });
                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.onLoadData()
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }

            })
            .catch((error) => {
                this.setState({
                    loading: false,
                });
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('CollectionPage----deleteCollection--', error)
            })
    }


    /**
     * onItemClick
     */
    onItemClick(data) {
        if (!data.obj_id) {
            DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
            return;
        }


        let _param = data.type === 2 ? {goods_id: data.obj_id} : {
            artID: data.obj_id,
            image: data.image,
            title: data.title,
        };
        this.props.navigator.push({
            component: data.type === 2 ? GoodsPage : ArticleDetail,
            params: _param,
        });


    }

    /**
     * 处理listView 的item
     */
    renderItem(rowData, position) {
        return (<TouchableOpacity
            onLongPress={() => this.setState({
                alertVisible: true,
                deleteData: {i: position, data: rowData},
            })}
            onPress={() => this.onItemClick(rowData)}
            style={{marginBottom: 16,}}
        >
            <View
                style={[StyleUtils.rowDirection, {
                    paddingLeft: 16,
                    paddingRight: 16,
                }]}>
                <View style={{padding: 4, backgroundColor: '#e9e9e9',}}>
                    <Image
                        style={styles.image}
                        source={rowData.image ? {uri: IMAGE_URL + rowData.image} : require('../../res/images/ic_image_fail_simlal.png')}
                    />
                </View>

                <View style={[StyleUtils.flex]}>
                    <Text numberOfLines={1}
                          style={[StyleUtils.smallFont, styles.text, {paddingBottom: 0}]}>{rowData.title}</Text>

                    <Text numberOfLines={1}
                          style={[StyleUtils.smallFont, styles.minContentText,]}>
                        ( {I18n.t(rowData.type === 2 ? 'default.product' : 'default.article')} )
                    </Text>

                    <Text numberOfLines={1}
                          style={[StyleUtils.smallFont, styles.minContentText,]}>{rowData.update_time}</Text>
                </View>


            </View>
        </TouchableOpacity>)
    }

    render() {
        return (<View style={StyleUtils.flex}>

            <Navigation
                title={I18n.t('default.favourites')}
                onClickLeftBtn={() => this.props.navigator.pop()}/>

            <ListView
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.refreshing}
                        onRefresh={() => this.onLoadData()}
                    />
                }
                style={{paddingTop: 16}}
                renderRow={(rowData, sectionID, rowID) => this.renderItem(rowData, rowID)}
                dataSource={this.state.dataSource}/>

            <AlertDialog
                leftBtnOnclick={() => {
                    this.setState({alertVisible: false},
                        this.deleteCollection(this.state.deleteData.data, this.state.deleteData.i))

                }}
                leftSts={I18n.t('default.delete')}
                contentTv={I18n.t('default.deleteNote')}
                visible={this.state.alertVisible}
                requestClose={() => this.setState({alertVisible: false})}/>
        </View>)
    }

}
const styles = StyleSheet.create({

    image: {
        width: 90,
        height: 90,
        resizeMode: 'contain',
    },
    text: {
        fontSize: 16,
        padding: 8,
        color: '#333'
    },
    minContentText: {
        fontSize: 14,
        padding: 8,
        paddingTop: 4,
        color: '#969696',
    },

});